<template>
	<view class="container">
	<view class="header">
		<text class="title">新增盘点单</text>
		<view class="save-btn" @click="saveInventory">
			<text class="save-text">保存</text>
		</view>
	</view>

		<view class="content">
			<!-- 基本信息 -->
			<view class="section">
				<view class="section-title">基本信息</view>
				<view class="form-grid">
					<view class="field">
						<text class="label">计划盘点时间</text>
						<picker mode="multiSelector" :range="dateTimeRange" :value="plannedDateIdx" @change="onPickPlannedDate" v-if="dateTimeRange.length > 0">
							<view class="input picker">{{ form.plannedDate || '请选择计划时间' }}</view>
						</picker>
						<view class="input picker" v-else>加载中...</view>
					</view>
					<view class="field">
						<text class="label">备件仓库</text>
						<picker mode="selector" :range="warehouseList" range-key="name" @change="onWarehouseChange">
							<view class="input picker">{{ warehouseName || '请选择仓库' }}</view>
						</picker>
					</view>
				</view>
			</view>

			<!-- 备注信息 -->
			<view class="section">
				<view class="section-title">备注信息</view>
				<view class="remark-field">
					<textarea class="textarea" v-model="form.remark" placeholder="请输入备注信息（可选）" maxlength="200"></textarea>
					<text class="char-count">{{ form.remark.length }}/200</text>
				</view>
			</view>

			<!-- 备件信息 -->
			<view class="section">
				<view class="section-header">
					<text class="section-title">备件信息</text>
					<button class="select-parts-btn" @click="selectParts">选择备件</button>
				</view>
				
				<!-- 备件表格 -->
				<view class="parts-table" v-if="partsList.length > 0">
					<view class="table-header">
						<text class="header-cell">备件编号</text>
						<text class="header-cell">备件名称</text>
						<text class="header-cell">规格型号</text>
						<text class="header-cell">备件类型</text>
						<text class="header-cell">库存数量</text>
					</view>
					<view class="table-body">
						<view class="table-row" v-for="(part, index) in partsList" :key="index">
							<text class="table-cell">{{ part.partCode }}</text>
							<text class="table-cell">{{ part.partName }}</text>
							<text class="table-cell">{{ part.specification }}</text>
							<text class="table-cell">{{ getPartTypeName(part.partType) }}</text>
							<text class="table-cell">{{ part.quantity }}</text>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view class="empty-parts" v-else>
					<text class="empty-text">暂无数据</text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>
	</view>
</template>

<script>
import { addInventory } from '@/api/inventory/inventory.js'
import { listWarehouseDTO } from '@/api/inventory/warehouse.js'

export default {
		data() {
			return {
				loading: false,
			form: {
				sessionNo: '',
				plannedDate: '',
				warehouseCode: '',
				inventoryUser: '',
				remark: ''
			},
			dateTimeRange: [],
			plannedDateIdx: [0,0,0,0,0,0],
				warehouseList: [],
				warehouseName: '',
				// 备件列表
				partsList: [],
			// 仓库映射
			warehouseMapping: {
				'WH001': '主仓库',
				'WH002': '备用仓库',
				'WH003': '临时仓库',
				'MAIN': '主仓库',
				'BACKUP': '备用仓库',
				'TEMP': '临时仓库'
			},
			// 备件类型列表（从后端获取）
			partTypeList: []
			}
		},
	onLoad() {
		this.loadMeta()
		this.initForm()
		this.initDateTime()
		console.log('页面加载完成，dateTimeRange:', this.dateTimeRange);
	},
	methods: {
		async loadMeta() {
			// 并行加载仓库列表和备件类型列表
			try {
				console.log('开始加载元数据...')
				await Promise.all([
					this.loadWarehouses(),
					this.loadPartTypes()
				])
			} catch (e) {
				console.error('加载元数据失败:', e)
			}
		},

		// 加载仓库列表
		async loadWarehouses() {
			try {
				console.log('开始加载仓库列表...')
				const r = await listWarehouseDTO({})
				console.log('仓库API返回:', r)

				if (r && r.code === 200 && r.data && Array.isArray(r.data)) {
					this.warehouseList = r.data.map(w => ({
						code: w.warehouseCode || w.code || w.id || '',
						name: w.warehouseName || w.name || w.label || w.text
					}))
					console.log('仓库列表处理完成:', this.warehouseList)
					console.log('仓库列表长度:', this.warehouseList.length)
				} else {
					console.log('仓库数据为空或格式不正确，响应:', r)
					this.warehouseList = []
				}
			} catch (e) {
				console.error('加载仓库列表失败:', e)
				this.warehouseList = []
			}
		},

		// 加载备件类型列表
		async loadPartTypes() {
			try {
				console.log('开始加载备件类型列表...')
				const { listPartType } = await import('@/api/inventory/partType.js')
				const response = await listPartType({})
				console.log('备件类型API返回 (原始):', response)

				if (response && response.code === 200) {
					const types = response.rows || response.data || []
					this.partTypeList = types.map(type => ({
						code: type.code || type.typeCode || type.id,
						name: type.name || type.typeName || type.label
					}))
					console.log('备件类型列表处理完成 (格式化后):', this.partTypeList)
				} else {
					console.log('备件类型数据为空或格式不正确，响应:', response)
					this.partTypeList = []
				}
			} catch (e) {
				console.error('加载备件类型列表失败:', e)
				this.partTypeList = []
			}
		},

		// 初始化表单
		initForm() {
			// 设置当前用户（从本地存储获取）
			const userInfo = uni.getStorageSync('userInfo') || {}
			this.form.inventoryUser = userInfo.userName || userInfo.nickName || userInfo.name || '若依'
			
			// 清空备件列表，确保没有假数据
			this.partsList = []
			
			console.log('初始化表单:', this.form)
			console.log('用户信息:', userInfo)
			console.log('备件列表已清空:', this.partsList)
		},

		// 初始化日期时间选择器
		initDateTime() {
			const years = []
			const months = []
			const days = []
			const hours = []
			const minutes = []
			const seconds = []
			const now = new Date()
			const y0 = now.getFullYear() - 1
			for (let y = y0; y <= y0 + 3; y++) years.push(String(y))
			for (let m = 1; m <= 12; m++) months.push(String(m).padStart(2,'0'))
			for (let d = 1; d <= 31; d++) days.push(String(d).padStart(2,'0'))
			for (let h = 0; h < 24; h++) hours.push(String(h).padStart(2,'0'))
			for (let i = 0; i < 60; i++) { 
				minutes.push(String(i).padStart(2,'0')); 
				seconds.push(String(i).padStart(2,'0')) 
			}
			this.dateTimeRange = [years, months, days, hours, minutes, seconds]
			console.log('日期时间轮盘初始化完成:', this.dateTimeRange);
			console.log('年:', years.length, '月:', months.length, '日:', days.length, '时:', hours.length, '分:', minutes.length, '秒:', seconds.length);
		},

		onPickPlannedDate(e) {
			console.log('轮盘选择事件触发:', e.detail.value);
			const [y,m,d,h,i,s] = this.pickToYmdHms(e.detail.value)
			this.plannedDateIdx = e.detail.value
			this.form.plannedDate = `${y}-${m}-${d} ${h}:${i}:${s}`
			console.log('设置计划盘点时间:', this.form.plannedDate);
			console.log('年月日时分秒:', y, m, d, h, i, s);
		},

		pickToYmdHms(idxArr) {
			console.log('pickToYmdHms 输入:', idxArr);
			console.log('dateTimeRange 长度:', this.dateTimeRange ? this.dateTimeRange.length : 'undefined');
			
			if (!this.dateTimeRange || this.dateTimeRange.length < 6) {
				console.log('重新初始化 dateTimeRange');
				this.initDateTime();
			}
			
			const safeIdx = (v) => Number(v || 0)
			try {
				const y = this.dateTimeRange[0][safeIdx(idxArr[0])]
				const m = this.dateTimeRange[1][safeIdx(idxArr[1])]
				const d = this.dateTimeRange[2][safeIdx(idxArr[2])]
				const h = this.dateTimeRange[3][safeIdx(idxArr[3])]
				const i = this.dateTimeRange[4][safeIdx(idxArr[4])]
				const s = this.dateTimeRange[5][safeIdx(idxArr[5])]
				console.log('转换结果:', [y,m,d,h,i,s]);
				return [y,m,d,h,i,s]
			} catch (error) {
				console.error('pickToYmdHms 错误:', error);
				return ['2025', '10', '19', '00', '00', '00'];
			}
		},

		onWarehouseChange(e) {
			const index = e.detail.value
			const selected = this.warehouseList[index]
			this.form.warehouseCode = selected.code
			this.warehouseName = selected.name
		},

		// 选择备件
		async selectParts() {
			console.log('选择备件方法被调用');
			try {
				// 调用真实的备件API获取数据
				const res = await this.loadPartsData();
				console.log('备件数据加载结果:', res);
				
				if (res && res.length > 0) {
					// 确保每个备件都有正确的字段，并补充缺失的字段
					const validParts = res.filter(part => part.partCode && part.partName).map(part => ({
						...part,
						specification: part.specification || '暂无',
						partType: part.partType || 'UNKNOWN',
						quantity: part.quantity || 0
					}));
					console.log('有效备件数据:', validParts);
					
					if (validParts.length > 0) {
						uni.showActionSheet({
							itemList: validParts.map(part => `${part.partCode} - ${part.partName}`),
							success: (actionRes) => {
								const selectedPart = validParts[actionRes.tapIndex];
								console.log('选择的备件:', selectedPart);
								
								// 检查是否已存在
								const existingIndex = this.partsList.findIndex(part => part.partCode === selectedPart.partCode);
								if (existingIndex >= 0) {
									uni.showToast({
										title: '该备件已存在',
										icon: 'none'
									});
									return;
								}
								
								// 添加到列表
								this.partsList.push(selectedPart);
								uni.showToast({
									title: '备件添加成功',
									icon: 'success'
								});
							}
						});
					} else {
						uni.showToast({
							title: '备件数据格式错误',
							icon: 'none'
						});
					}
				} else {
					uni.showToast({
						title: '暂无备件数据',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载备件数据失败:', error);
				uni.showToast({
					title: '加载备件失败',
					icon: 'none'
				});
			}
		},

		// 加载备件数据 - 从后端API获取
		async loadPartsData() {
			try {
				// 调用真实的备件API
				const { listPart } = await import('@/api/inventory/part.js');
				const response = await listPart({});
				console.log('备件API返回:', response);
				
				if (response && response.code === 200) {
					const parts = response.rows || response.data || [];
					console.log('备件原始数据:', parts);
					
					if (parts.length > 0) {
						// 转换数据格式，确保字段映射正确
						const formattedParts = parts.map(item => {
							const partCode = item.partCode || item.partNo || item.code || item.id || '';
							const partName = item.partName || item.name || item.partName || '';
							const specification = item.specification || item.specNo || item.spec || item.model || '';
							const partType = item.partType || item.partTypeCode || item.typeCode || item.type || '';
							const quantity = item.quantity || item.stockTotal || item.stock || item.qty || 0;
							
							console.log('备件原始数据:', item);
							console.log('映射后数据:', { partCode, partName, specification, partType, quantity });
							
							return {
								partCode,
								partName,
								specification,
								partType,
								quantity
							};
						});
						
						console.log('格式化后的备件数据:', formattedParts);
						return formattedParts;
					} else {
						console.log('备件数据为空');
						return [];
					}
				} else {
					console.log('API返回错误:', response);
					return [];
				}
			} catch (error) {
				console.error('加载备件数据失败:', error);
				return [];
			}
		},

		async saveInventory() {
			try {
				// 验证必填字段
				if (!this.form.plannedDate) {
					uni.showToast({ title: '请选择计划盘点时间', icon: 'none' })
					return
				}
				if (!this.form.warehouseCode) {
					uni.showToast({ title: '请选择备件仓库', icon: 'none' })
					return
				}
				if (this.partsList.length === 0) {
					uni.showToast({ title: '请至少选择一个备件', icon: 'none' })
					return
				}
				
				const payload = {
					sessionNo: this.form.sessionNo || '', // 后端会自动生成
					plannedDate: this.form.plannedDate,
					warehouseCode: this.form.warehouseCode,
					inventoryUser: this.form.inventoryUser,
					remark: this.form.remark || '',
					status: 'PENDING', // 默认状态为待盘点
					partList: this.partsList.map(part => ({
						partNo: part.partCode,  // 后端期望的字段名是partNo
						partName: part.partName,
						specification: part.specification,
						partType: part.partType,
						theoreticalQty: part.quantity
					}))
				}
				
				console.log('提交数据:', payload)
				console.log('备件列表:', this.partsList)
				
				uni.showLoading({ title: '保存中...' })
				const r = await addInventory(payload)
				uni.hideLoading()
				
				if (r && r.code === 200) {
					uni.showToast({ title: '保存成功', icon: 'success' })
					setTimeout(() => uni.navigateBack(), 1500)
				} else {
					uni.showToast({ title: r.msg || '保存失败', icon: 'none' })
				}
			} catch (e) {
				uni.hideLoading()
				console.error('保存失败:', e)
				uni.showToast({ title: '保存失败: ' + (e.message || '未知错误'), icon: 'none' })
			}
		},

		goBack() {
			uni.navigateBack()
		},

		// 获取备件类型中文名称
		getPartTypeName(typeCode) {
			if (!typeCode) return ''
			console.log('查找备件类型:', typeCode, '当前备件类型列表:', this.partTypeList)
			
			// 首先尝试从后端数据中查找
			const partType = this.partTypeList.find(type => type.code === typeCode)
			if (partType) {
				console.log('从后端数据找到备件类型:', partType.name)
				return partType.name
			}
			
			// 如果后端数据为空，使用备用映射
			const fallbackMapping = {
				'BEARING': '轴承',
				'SEAL': '密封件',
				'FILTER': '过滤器',
				'BELT': '皮带',
				'CHAIN': '链条',
				'GEAR': '齿轮',
				'VALVE': '阀门',
				'PUMP': '泵',
				'MOTOR': '电机',
				'SENSOR': '传感器',
				'CABLE': '电缆',
				'TOOL': '工具',
				'CONSUMABLE': '消耗品',
				'SPARE': '备件',
				'REPAIR': '维修件'
			}
			
			const result = fallbackMapping[typeCode] || typeCode
			console.log('备件类型映射结果:', result)
			return result
		},

	}
}
</script>

<style>
	/* 备件信息样式 */
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15px;
	}

	.select-parts-btn {
		background-color: #007bff;
		color: white;
		border: none;
		border-radius: 6px;
		padding: 8px 16px;
		font-size: 14px;
		cursor: pointer;
	}

	.parts-table {
		border: 1px solid #dee2e6;
		border-radius: 8px;
		overflow: hidden;
	}

	.table-header {
		display: flex;
		background-color: #f8f9fa;
	}

	.header-cell {
		flex: 1;
		padding: 12px 8px;
		font-size: 14px;
		font-weight: bold;
		color: #333;
		text-align: center;
		border-right: 1px solid #dee2e6;
	}

	.header-cell:last-child {
		border-right: none;
	}

	.table-body {
		display: flex;
		flex-direction: column;
	}

	.table-row {
		display: flex;
		border-bottom: 1px solid #dee2e6;
	}

	.table-row:last-child {
		border-bottom: none;
	}

	.table-cell {
		flex: 1;
		padding: 12px 8px;
		font-size: 14px;
		color: #333;
		text-align: center;
		border-right: 1px solid #dee2e6;
		word-break: break-all;
	}

	.table-cell:last-child {
		border-right: none;
	}

	.empty-parts {
		text-align: center;
		padding: 40px 20px;
		color: #999;
	}

	.empty-text {
		font-size: 14px;
	}

	/* 禁用状态样式 */
	.input.disabled {
		background-color: #f5f5f5;
		color: #999;
		cursor: not-allowed;
	}

</style>

<style scoped>
.container {
	min-height: 100vh;
	background-color: #f5f6f7;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #fff;
	border-bottom: 1rpx solid #eee;
}

.save-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.save-text {
	font-size: 28rpx;
	color: #4a94ff;
	font-weight: 500;
}

.content {
	padding: 20rpx;
}

.section {
	background: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	padding: 30rpx 30rpx 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-grid {
	padding: 20rpx 30rpx 30rpx;
}

.field {
	margin-bottom: 30rpx;
}

.field:last-child {
	margin-bottom: 0;
}

.label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
	margin-bottom: 15rpx;
}

.input {
	width: 100%;
	height: 80rpx;
	background: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
}

.input.picker {
	display: flex;
	align-items: center;
	color: #666;
}

.input:disabled {
	background: #f5f5f5;
	color: #999;
}

.remark-field {
	padding: 20rpx 30rpx 30rpx;
	position: relative;
}

.textarea {
	width: 100%;
	min-height: 200rpx;
	background: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 20rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
	resize: none;
}

.char-count {
	position: absolute;
	bottom: 40rpx;
	right: 40rpx;
	font-size: 24rpx;
	color: #999;
}

.loading {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}
</style>
